/*
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-05-12 12:09:01
 * @LastEditTime: 2023-08-10 15:47:56
 */
import { _, buildUUID, ikArray, paramType } from 'iking-utils'
import { ElMessage } from 'element-plus'
import { formApi } from '@/MainApp/apis/approve-center'

export const useLoadEditData = () => {
  const flowStore = useFlowStore()
  const loadingEdit = ref(false)
  const router = useRouter()

  const resetUUID = (data: any, parentId?: string) => {
    if (paramType.isArray(data)) {
      data?.forEach((item: any) => {
        item.id = buildUUID()
        item.parentId = parentId || null
        if (item.children)
          resetUUID(item.children, item.id)
        if (item.branchs)
          resetUUID(item.branchs, item.id)
      })
    }
    else {
      data.id = buildUUID()
      data.parentId = parentId || null
      if (data.children)
        resetUUID(data.children, data.id)
      if (data.branchs)
        resetUUID(data.branchs, data.id)
    }
  }

  // 编辑
  const handEditFlow = async (row: { id: string; }, toStepOne = true) => {
    loadingEdit.value = true // 加载中...
    // 获取表单详情
    const { success, data, msg } = await formApi.getFormDetail(row.id)
    localStorage.setItem('formViewConfig', data.formViewConfig?.property || '')
    try {
      if (success) {
        if (data) {
          const formObj = JSON.parse(data?.formViewConfig?.property || '{}')
          const PROCESS = JSON.parse(data?.process?.property || '{}')?.process || []
          resetUUID(PROCESS)

          const copyData = _.cloneDeep(data)
          const viewConfig = _.cloneDeep(data.formViewConfig)
          delete copyData.formViewConfig
          delete copyData.process
          delete copyData.formAdvanceConfigDTO

          copyData?.initiators?.forEach((initiator: any) => {
            const { initiatorId, initiatorName, initiatorType } = initiator
            initiator.elementName = initiatorName
            initiator.elementId = initiatorId
            initiator.elementType = initiatorType
          })
          copyData.managers?.forEach((initiator: any) => {
            const { managerId, managerName, managerType } = initiator
            initiator.elementName = managerName
            initiator.elementId = managerId
            initiator.elementType = managerType
          })
          const form = {
            base: {
              ...copyData,
              initiatorsName: ikArray.listToString(
                copyData?.initiators,
                'elementName',
                ', ',
                ''
              ),
              managersName: ikArray.listToString(
                copyData?.managers,
                'elementName',
                ', ',
                ''
              )
            },
            // advance: data.formAdvanceConfigDTO,
            formItems: viewConfig?.widgets || formObj?.widgetList || [],
            process: PROCESS
          }
          flowStore.loadForm(form)

          flowStore.setForm({
            id: data?.formViewConfig?.id,
            formId: data?.formViewConfig?.formId,
            formConfig: formObj?.formConfig,
            widgetList: viewConfig?.widgets || formObj?.widgetList
          })

          // 设置高级配置
          flowStore.setAdvance(data.formAdvanceConfig)
          if (toStepOne) {
            router.push({
              name: 'EditForm',
              query: { type: data?.type, id: row.id, isEdit: 1 }
            })
          }
        }
        loadingEdit.value = false
      }
      else {
        ElMessage.error(msg)
        loadingEdit.value = false
      }
    }
    catch (error) {
      console.info('error: ', error)
    }
  }

  return {
    loadingEdit,
    handEditFlow
  }
}
